<?php
namespace frontend\modules\site\controllers;

use backend\modules\datainfo\models\ClickInfo;
use common\models\Wxuser;
use frontend\modules\base\controllers\BaseController;
use frontend\modules\goods\models\Goods;
use frontend\modules\marketing\models\ShareReb;
use frontend\modules\orders\models\OrderGoods;
use frontend\modules\orders\models\OrderInfo;
use frontend\token\tokenCheck;
use Yii;
use yii\base\Exception;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use dosamigos\qrcode\QrCode;

/**
 * 站点入口验证
 *
 * Class SiteController
 * @package frontend\modules\site\controllers
 */
class SiteController extends BaseController
{
    public $enableCsrfValidation = false;
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'signup','signuptest'],
                'rules' => [
                    [
                        'actions' => ['signup','signuptest'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * 微信授权登录，访问页面入口
     *
     * @desc 微信授权登录，访问页面入口，不需要其他参数验证，微信自己验证发送code,微信第二次访问时，不需要授权登录，需传入openid,userid
     * @param string $code |微信生成的code|yes|用户授权登录，向回调域发送code，回调域就是我们的程序地址|
     * @param string $acccess_token |第二次入口access_token|no|入口
     * @return array data 返回数据|验证信息
     * @return string data[].userid 用户ID
     * @return string data[].openid 用户名字
     * @return string data[].access_token 用户令牌
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 500 服务器内部错误
     * @return mixed
     */
//    public function actionSignup()
//    {
//        $session = Yii::$app->session;
//        $unionid=$session->get('unionid');
//        $userid = $session->get('userid');
//        if($unionid&&$userid)
//        {
//            $user = Wxuser::find()->where(['unionid'=>$unionid])->one();
//            return $this->renderPartial('index',
//                ['unionid'=>$unionid,'userid'=>$userid,'_csrf'=>Yii::$app->request->getCsrfToken(),'access_token'=>$user->access_token]
//            );
//        }
//        $code = isset($_GET['code'])?$_GET['code']:'';
//        if($code) {
//            /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
//            $wechat = Yii::$app->wechat;
//            try{
//                $wxInfo = $wechat->getOauth2AccessToken($code);
//                $unionid = $wxInfo['unionid'];
//                $user = Wxuser::find()->where(['unionid'=>$unionid])->one();
//
//                if($unionid==null){
//                    $message = ['code'=>500,'message'=>'code过期'];
//                    print_r($message);exit;
//                }
//                if($user){
//                    $this->setSession($user);
//                    return $this->renderPartial('index',
//                        ['unionid'=>$user->unionid,'userid'=>$user->id,'_csrf'=>Yii::$app->request->getCsrfToken(),'access_token'=>$user->access_token]
//                    );
//                }
//                $menberInfo = $wechat->getSnsMemberInfo($wxInfo['openid']);
//                $user = new Wxuser();
//                $user->openid = $wxInfo['openid'];
//                $user->unionid = $unionid;
//                $user->wx_name = $menberInfo['nickname'];
//                $user->wx_images = $menberInfo['headimgurl'];
//                $user->wx_name = $menberInfo['nickname'];
//                $user->username = $menberInfo['nickname'];
//                $user->sex = $menberInfo['sex'];
//                if($user->save()) {
//                    $this->setSession($user);
////                    $message = ['code'=>200,'message'=>'登录成功','data'=>[]];
//                    return $this->renderPartial('index',
//                        ['unionid'=>$user->unionid,'userid'=>$user->id,'_csrf'=>Yii::$app->request->getCsrfToken(),'access_token'=>$user->access_token]
//                    );
//                }else {
//                    throw new Exception(json_encode($user->errors));
//                }
//            } catch(Exception $e){
//                $message = ['code'=>500,'message'=>$e->getMessage()];
//                print_r($message);exit;
//            }
//        }
//
//        $message = ['code'=>500,'message'=>'访问路径非法！'];
//        print_r($message);exit;
//    }

    /**
     * @param $user
     */
    public function setSession($user)
    {
        $session = Yii::$app->session;
        $session->set('userid',$user->id);
        $session->set('openid',$user->openid);
        $session->set('unionid',$user->unionid);
        $session->set('nickname',$user->wx_name);
        $session->set('headimgurl',$user->wx_images);
        $session->set('sex',$user->sex);
    }

    /**
     * 刷新令牌token
     *
     * @desc 用户令牌过期，再次请求生成令牌，有效期2小时
     * @param string $userid |用户ID|yes|其他说明|
     * @param string $unionid |微信ID|yes|其他说明|
     * @return array data 返回数据|验证信息
     * @return string data[].userid 用户ID
     * @return string data[].unionid 用户名字
     * @return string data[].access_token 用户令牌
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 500 服务器内部错误
     *
     */
    public function actionReftoken()
    {
        $post = Yii::$app->request->post();
        $token = new \frontend\token\tokenCheck();
        $userid  =  isset($post['userid'])?$post['userid']:'';
        if($userid){
            $user = $token->reftoken($userid);
            if($user){
                $message = ['code'=>200,'message'=>'token刷新成功','data'=>['openid'=>$user->openid,'userid'=>$user->id,'access_token'=>$user->access_token]];
                return json_encode($message);
            }
            $message = ['code'=>500,'message'=>'保存失败'];
            return json_encode($message);
        }
        $message = ['code'=>500,'message'=>'参数不完整！'];
        return json_encode($message);
    }

    /**
     * 刷新令牌token
     *
     * @desc 用户令牌过期，再次请求生成令牌，有效期2小时
     * @param string $userid |用户ID|yes|其他说明|
     * @param string $unionid |微信ID|yes|其他说明|
     * @return array data 返回数据|验证信息
     * @return string data[].userid 用户ID
     * @return string data[].unionid 用户名字
     * @return string data[].access_token 用户令牌
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 500 服务器内部错误
     *
     */
    public function actionReftoken2()
    {
        $token = new \frontend\token\tokenCheck();
        $userid  =  \Yii::$app->UserInfo->userid;
        if(!$userid) {
            return $this->redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5dee5a1c01f37b68&redirect_uri=".Yii::$app->params['domurl']."wx%2Ffrontend%2Fweb%2Findex.php%3Fr%3Dsite%252Fsite%252Findex&time=1100&response_type=code&scope=snsapi_userinfo&state=authorize#wechat_redirect");
        }

        if($userid){
            $user = $token->reftoken($userid);
            if($user){
                $message = ['code'=>200,'message'=>'token刷新成功','data'=>['userid'=>$user->id,'access_token'=>$user->access_token]];
                return json_encode($message);
            }
            $message = ['code'=>500,'message'=>'保存失败'];
            return json_encode($message);
        }
        $message = ['code'=>500,'message'=>'参数不完整！'];
        return json_encode($message);
    }

    /**
     * @desc 验证令牌是否过期，是否正确通过
     *
     * @param string $userid |用户ID|yes|40位|
     * @param string $access_token |令牌access_token|yes|32位|
     * @return array data 返回数据|验证信息
     * @return string data[].userid 用户ID
     * @return string data[].openid 用户名字
     * @return string data[].access_token 用户令牌
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 400 token验证失败
     * @exception 200 成功获取
     * @exception 500 服务器内部错误
     */
    public function actionChecktoken()
    {
        $post = Yii::$app->request->post();
        $userid = isset($post['userid'])?$post['userid']:'';
        $access_token = isset($post['access_token'])?$post['access_token']:'';
        if($access_token&&$userid){
            $token = new tokenCheck();
            $userinfo = $token->check($userid,$access_token);
            if($userinfo){
                $message = ['code'=>200,'message'=>'token验证成功','data'=>['openid'=>$userinfo->openid,'userid'=>$userinfo->id,'access_token'=>$userinfo->access_token]];
                return json_encode($message);
            }
            $message = ['code'=>400,'message'=>'token验证失败'];
            return json_encode($message);
        } else {
            $message = ['code'=>500,'message'=>'token验证失败，参数传递错误'];
            return json_encode($message);
        }
    }

    /**
     * 获取用户授权url
     *
     * @return array data 返回数据|验证信息
     * @return string url 路径
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 500 服务器内部错误
     * @return string
     */
    public function actionGetwurl()
    {
        /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
        $wechat = Yii::$app->wechat;
        $url = $wechat->getOauth2AuthorizeUrl(Yii::$app->params['domurl'].'wx/frontend/web/index.php?r=site%2Fsite%2Fdetail&qcode=cbfe7330-e0a6-11e7-85e3-a3ad0180d146','authorize','snsapi_userinfo');
        if($url){
            $message = ['code'=>200,'url'=>$url];
            return json_encode($message);
        }
        $message = ['code'=>500,'message'=>'token验证失败，参数传递错误'];
        return json_encode($message);
    }

    /**
     * 测试接口，不用在微信打开
     *
     * @desc 后台直接返回有效数据包括（token，userid，unionid等）
     * @return array data 返回数据|验证信息
     * @return string data[].userid 用户ID
     * @return string data[].openid 用户名字
     * @return string data[].access_token 用户令牌
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 500 服务器内部错误
     * @return mixed
     */
    public function actionSignuptest()
    {
        $session = Yii::$app->session;
        $unionid=$session->get('unionid');
        $userid = $session->get('userid');
        if($unionid&&$userid)
        {
            $user = Wxuser::find()->where(['unionid'=>$unionid])->one();
            return $this->renderPartial('indextest',
                ['unionid'=>$unionid,'userid'=>$userid,'_csrf'=>Yii::$app->request->getCsrfToken(),'access_token'=>$user->access_token]
            );
        }
        $user = Wxuser::find()->where(['unionid'=>'o0NVevyCkCI7jR6cLMlIz8XjTy34'])->one();
        return $this->renderPartial('indextest',
            ['unionid'=>'o0NVevyCkCI7jR6cLMlIz8XjTy34','userid'=>'cb90c740-c90a-11e7-a83c-e1886effa0e6','_csrf'=>Yii::$app->request->getCsrfToken(),'access_token'=>$user->access_token]
        );
    }

    /***
     * 商品详情页附带推荐人信息,详情页入口，微信授权登录，访问页面入口
     *
     *
     * @desc 微信授权登录详情页入口
     * @return array data[] 属性列表多维数组
     * @return string message 提示信息
     * @exception 200 参数传递错误
     * @exception 500 服务器内部错误
     * @return string
     */
    public function actionGoodstemp()
    {
        $session = Yii::$app->session;
        $unionid=$session->get('unionid');
        $userid = $session->get('userid');
        $refereid = $session->get('qcode');
        if($unionid&&$userid)
        {
            $user = Wxuser::find()->where(['unionid'=>$unionid])->one();
            $refereInfo = Wxuser::find()->where(['id'=>$refereid])->asArray()->one();
            return $this->renderPartial('goods_detail',
                ['unionid'=>$user->unionid,'userid'=>$user->id,'_csrf'=>Yii::$app->request->getCsrfToken(),'access_token'=>$user->access_token,'refereInfo'=>$refereInfo]
            );
        }
        $code = isset($_GET['code'])?$_GET['code']:'';
        $qcode = isset($_GET['userid'])?$_GET['userid']:'';
        $goods_id = isset($_GET['goods_id'])?$_GET['goods_id']:'';
        if($code&$goods_id&&$qcode) {
            /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
            $wechat = Yii::$app->wechat;
            try{
                $wxInfo = $wechat->getOauth2AccessToken($code);
                $unionid = $wxInfo['unionid'];
                $user = Wxuser::find()->where(['unionid'=>$unionid])->one();

                if($unionid==null){
                    $message = ['code'=>500,'message'=>'code过期'];
                    print_r($message);exit;
                }
                if($user){
                    $this->setSession($user);
                    $refereInfo = $this->getRefereInfo($goods_id,$qcode);
                    if($refereInfo) {
                        return $this->renderPartial('goods_detail',
                            ['unionid'=>$user->unionid,'userid'=>$user->id,'_csrf'=>Yii::$app->request->getCsrfToken(),'access_token'=>$user->access_token,'refereInfo'=>$refereInfo]
                        );
                    } else{
                        return false;
                    }
                }
                $menberInfo = $wechat->getSnsMemberInfo($wxInfo['openid'],$wxInfo['access_token']);
                if($menberInfo['subscribe']==0){
                    return $this->renderPartial('index',
                        ['unionid'=>'','userid'=>'','_csrf'=>'','access_token'=>'']
                    );
                }
                $user = new Wxuser();
                $user->openid = $wxInfo['openid'];
                $user->unionid = $unionid;
                $user->wx_name = $menberInfo['nickname'];
                $user->wx_images = $menberInfo['headimgurl'];
                $user->wx_name = $menberInfo['nickname'];
                $user->username = $menberInfo['nickname'];
                $user->sex = $menberInfo['sex'];
                if($user->save()) {
                    $this->setSession($user);
                    $refereInfo = $this->getRefereInfo($goods_id,$qcode);
                    if($refereInfo) {
                        return $this->renderPartial('goods_detail',
                            ['unionid'=>$user->unionid,'userid'=>$user->id,'_csrf'=>Yii::$app->request->getCsrfToken(),'access_token'=>$user->access_token,'refereInfo'=>$refereInfo]
                        );
                    } else{
                        return false;
                    }

                }
            } catch(Exception $e){
                $message = ['code'=>500,'message'=>$e->getMessage()];
                print_r($message);exit;
            }
        } else {
            $message = ['code'=>500,'message'=>'缺少参数'];
            return json_encode($message);
        }
    }

    /**
     * 获取推荐人信息
     *
     * @param $goods_id
     * @param $qcode
     * @return array|bool|null|\yii\db\ActiveRecord
     */
    public function getRefereInfo($goods_id,$qcode)
    {
        $goods = Goods::find()->where(['goods_id'=>$goods_id])->asArray()->one();
        //获取推荐人
        $refereInfo = Wxuser::find()->where(['qcode'=>$qcode])->asArray()->one();
        if($refereInfo['is_gz']!==0){
            $this->userSave($refereInfo['openid']);
        }
        $num = $this->getGoodsReM($refereInfo['id'],$goods['attr_cat_id']);
        $session = Yii::$app->session;
        $session->set('qcode',$refereInfo['id']);
        $session->set('referename',$refereInfo['wx_name']);
        $session->set('refereimages',$refereInfo['wx_images']);

        if($num>0) {
            return $refereInfo;
        } else {
            return false;
        }
    }

    /**
     * 判断还剩多少返利次数
     *
     * @param $userid
     * @param $attr_cat_id
     * @return mixed
     */
    public function getGoodsReM($userid,$attr_cat_id)
    {
        $share_number = OrderGoods::find()->where(['user_id'=>$userid,'attr_cat_id'=>$attr_cat_id])->sum('goods_number');
        $count = ShareReb::find()->where(['user_id'=>$userid])->count();

        return $share_number*10-$count;
    }


    /**
     * @desc 获取二维码
     *
     * @param string $userid |用户ID|yes|40位|
     * @param string $access_token |令牌access_token|yes|32位|
     * @param string data[goods_id] |商品ID|yes|40位|
     * @return array data 二维码图片数据|图片数据
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 400 token验证失败
     * @exception 200 成功获取
     * @exception 500 服务器内部错误
     */
    public function actionCreateerw()
    {
        $userinfo = $this->checkAccessToken();
        if(is_object($userinfo)) {
            if ($userinfo) {
                $postData = $this->post['data'];
                $qcode = $userinfo->qcode;
                $goods_id = $postData['goods_id'];
                $url = Yii::$app->params['domurl'].'wx/frontend/web/index.php?r=wx/goto&qcode='.$qcode.'&goods_id='.$goods_id;

                $QR = \Yii::$app->basePath.'/web/images/111.png';
                $logo  = $userinfo->wx_images;
                QrCode::png($url,$QR);

                if ($logo !== FALSE) {
                    $QR = imagecreatefromstring(file_get_contents($QR));
                    $logo = imagecreatefromstring(file_get_contents($logo));
                    $QR_width = imagesx($QR);//二维码图片宽度
                    $QR_height = imagesy($QR);//二维码图片高度
                    $logo_width = imagesx($logo);//logo图片宽度
                    $logo_height = imagesy($logo);//logo图片高度
                    $logo_qr_width = $QR_width / 5;
                    $scale = $logo_width/$logo_qr_width;
                    $logo_qr_height = $logo_height/$scale;
                    $from_width = ($QR_width - $logo_qr_width) / 2;
                    //重新组合图片并调整大小
                    imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
                        $logo_qr_height, $logo_width, $logo_height);
                }
//输出图片
                imagepng($QR,\Yii::$app->basePath.'/web/images/tesss.png');
            }
        } else {
            return $userinfo;
        }
    }

    public function Test($url)
    {
        $session = Yii::$app->session;
        $unionid=$session->get('unionid');
        $userid = $session->get('userid');
        $refereid = $session->get('qcode');
        if($unionid&&$userid)
        {

        } else {
            /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
            $wechat = Yii::$app->wechat;
            $url = $wechat->getOauth2AuthorizeUrl($url);
        }
        return $this->redirect($url);
    }

    /**
     * 微信授权登录，访问页面入口
     *
     * @desc 微信授权登录，访问页面入口，不需要其他参数验证，微信自己验证发送code,微信第二次访问时，不需要授权登录，需传入openid,userid
     * @param string $code |微信生成的code|yes|用户授权登录，向回调域发送code，回调域就是我们的程序地址|
     * @param string $acccess_token |第二次入口access_token|no|入口
     * @return array data 返回数据|验证信息
     * @return string data[].userid 用户ID
     * @return string data[].openid 用户名字
     * @return string data[].access_token 用户令牌
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 500 服务器内部错误
     * @return mixed
     * @return \yii\web\Response
     * @throws Exception
     */
    public function actionIndex()
    {
        //用户第二次进入
        $session = Yii::$app->session;
        $openid=$session->get('openid');
        $userid = $session->get('userid');

        if($openid&&$userid)
        {
            $this->userSave($openid);
            return $this->redirect(Yii::$app->params['domurl']."wx/frontend/web/index.html?userid=".$userid);
        }

        //用户首次进入，获取用户微信信息，需要的code
        $code = isset($_GET['code'])?$_GET['code']:'';
        if($code) {
            /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
            $wechat = Yii::$app->wechat;
            $wxInfo = $wechat->getOauth2AccessToken($code);
            $menberInfo = $wechat->getSnsMemberInfo($wxInfo['openid'],$wxInfo['access_token']);
            $menberInfo = $this->getMenInfo($menberInfo);

                //获取用户信息，判断是否新用户，自动添加用户到数据库，页面显示已登陆状态
                $user = Wxuser::findOne(['openid'=>$menberInfo['openid']]);
                if($user) {
                    $this->setSession($user);
                    $this->userSave($menberInfo['openid']);
                    return $this->redirect(Yii::$app->params['domurl']."wx/frontend/web/index.html?userid=".$user->id);
                } else{
                    $user = new Wxuser();
                    $user->openid = $wxInfo['openid'];
                    $user->unionid = $openid;
                    $user->wx_name = $menberInfo['nickname'];
                    $user->wx_images = $menberInfo['headimgurl'];
                    $user->wx_name = $menberInfo['nickname'];
                    $user->username = $menberInfo['nickname'];
                    $user->sex = $menberInfo['sex'];
                    $user->is_gz = $menberInfo['is_gz'];

                    if($user->save()) {
                        $this->setSession($user);
                        return $this->redirect(Yii::$app->params['domurl']."wx/frontend/web/index.html?userid=".$user->id);
                    }else {
                        throw new Exception(json_encode($user->errors));
                    }
                }
            }
    }

    /**
     * 未关注用户数据填充
     *
     * @param $menberInfo
     * @return mixed
     */
    public function getMenInfo($menberInfo)
    {
        $menberInfo['nickname'] = isset($menberInfo['nickname'])?$menberInfo['nickname']:'小普匿名用户';
        $menberInfo['headimgurl'] = isset($menberInfo['headimgurl'])?$menberInfo['headimgurl']:Yii::$app->params['domurl'].'wx/backend/web/images/1.png';
        $menberInfo['unionid'] = isset($menberInfo['unionid'])?$menberInfo['unionid']:'xxx';
        $menberInfo['sex'] = isset($menberInfo['sex'])?$menberInfo['sex']:1;
        $menberInfo['is_gz'] = isset($menberInfo['subscribe'])?$menberInfo['subscribe']:0;
        return $menberInfo;
    }

    /**
     * 微信授权登录，访问页面入口
     *
     * @desc 微信授权登录，访问页面入口，不需要其他参数验证，微信自己验证发送code,微信第二次访问时，不需要授权登录，需传入openid,userid
     * @param string $code |微信生成的code|yes|用户授权登录，向回调域发送code，回调域就是我们的程序地址|
     * @param string $acccess_token |第二次入口access_token|no|入口
     * @return array data 返回数据|验证信息
     * @return string data[].userid 用户ID
     * @return string data[].openid 用户名字
     * @return string data[].access_token 用户令牌
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 500 服务器内部错误
     * @return mixed
     * @return \yii\web\Response
     * @throws Exception
     */
    public function actionDetail()
    {
        //用户第二次进入
        $session = Yii::$app->session;
        $openid=$session->get('openid');
        $userid = $session->get('userid');

        $qcode = isset($_GET['qcode'])?$_GET['qcode']:'';
        $ordersn = isset($_GET['ordersn'])?$_GET['ordersn']:'';

        if($qcode&&$ordersn){
            $session = Yii::$app->session;
            $refereInfo = Wxuser::findOne(['qcode'=>$qcode]);
            $session->set('ordersn',$ordersn);
            $session->set('qcode',$qcode);

            //完善用户信息
//            $refereInfo = $this->setCompliteInfo($refereInfo);

            $session->set('referename',$refereInfo['wx_name']);
            $session->set('refereimages',$refereInfo['wx_images']);
        }else{
            $ordersn = $session->get('ordersn');
            $qcode = $session->get('qcode');
        }
        if($openid&&$userid&&$qcode&&$ordersn)
        {
            $this->userSave($openid);
            return $this->redirect(Yii::$app->params['domurl']."wx/frontend/web/html/detail/goods_detail.html?id=8fc674d0-bcc0-11e8-b05d-a53f0a637c51&refereid=".$qcode."&userid=".$userid);
        }

        //用户首次进入，获取用户微信信息，需要的code
        $code = isset($_GET['code'])?$_GET['code']:'';
        $qcode = isset($_GET['qcode'])?$_GET['qcode']:'';
        $ordersn = isset($_GET['ordersn'])?$_GET['ordersn']:'';
        if($code&&$qcode&&$ordersn) {
            /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
            $wechat = Yii::$app->wechat;
            $wxInfo = $wechat->getOauth2AccessToken($code);
            $menberInfo = $wechat->getSnsMemberInfo($wxInfo['openid'],$wxInfo['access_token']);
            $menberInfo = $this->getMenInfo($menberInfo);

            //获取用户信息，判断是否新用户，自动添加用户到数据库，页面显示已登陆状态
            $user = Wxuser::findOne(['openid'=>$menberInfo['openid']]);
            if($user) {
//                ClickInfo::bClickInfo();
                $user->wx_name = $menberInfo['nickname'];
                $user->wx_images = $menberInfo['headimgurl'];
                $user->wx_name = $menberInfo['nickname'];
                $user->username = $menberInfo['nickname'];
                $user->sex = $menberInfo['sex'];
                $user->is_gz = $menberInfo['is_gz'];
                if($user->save()) {
                    $this->setSession($user);
                    $session = Yii::$app->session;
                    $refereInfo = Wxuser::findOne(['qcode'=>$qcode]);
                    $session->set('qcode',$qcode);
                    $session->set('ordersn',$ordersn);
                    $session->set('referename',$refereInfo['wx_name']);
                    $session->set('refereimages',$refereInfo['wx_images']);
                    return $this->redirect(Yii::$app->params['domurl']."wx/frontend/web/html/detail/goods_detail.html?id=8fc674d0-bcc0-11e8-b05d-a53f0a637c51&refereid=".$qcode."&userid=".$user->id);
                }else{
                    throw new Exception(json_encode($user->errors));
                }
            } else {
                $user = new Wxuser();
                $user->openid = $wxInfo['openid'];
                $user->unionid = $openid;
                $user->wx_name = $menberInfo['nickname'];
                $user->wx_images = $menberInfo['headimgurl'];
                $user->wx_name = $menberInfo['nickname'];
                $user->username = $menberInfo['nickname'];
                $user->sex = $menberInfo['sex'];
                $user->is_gz = $menberInfo['is_gz'];
                if($user->save()) {
                    $this->setSession($user);

//                    ClickInfo::bClickInfo();

                    $session = Yii::$app->session;
                    $refereInfo = Wxuser::findOne(['qcode'=>$qcode]);
                    $session->set('qcode',$qcode);
                    $session->set('ordersn',$ordersn);
                    $session->set('referename',$refereInfo['wx_name']);
                    $session->set('refereimages',$refereInfo['wx_images']);
                    return $this->redirect(Yii::$app->params['domurl']."wx/frontend/web/html/detail/goods_detail.html?id=8fc674d0-bcc0-11e8-b05d-a53f0a637c51&refereid=".$qcode."&userid=".$user->id);
                }else {
                    throw new Exception(json_encode($user->errors));
                }
            }
        } else {
            return 'aaa';
        }
    }

    public function setCompliteInfo($refereInfo){
        $wx_name = isset($refereInfo['wx_name'])?$refereInfo['wx_name']:'';
        $wx_image = isset($refereInfo['wx_name'])?$refereInfo['wx_images']:'';
        if($wx_name==''||$wx_image==''){
            /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
            $wechat = Yii::$app->wechat;
            $menberInfo = $wechat->getMemberInfo($refereInfo['openid']);

        }
    }

    public function actionGowxd()
    {
        //用户第二次进入
        $session = Yii::$app->session;
        $openid=$session->get('openid');
        $userid = $session->get('userid');

        $qcode = isset($_GET['qcode'])?$_GET['qcode']:'';
        $ordersn = isset($_GET['ordersn'])?$_GET['ordersn']:'';
        if($qcode){
            $session = Yii::$app->session;
            $refereInfo = Wxuser::findOne(['qcode'=>$qcode]);
            $session->set('ordersn',$ordersn);
            $session->set('qcode',$qcode);
            $session->set('referename',$refereInfo['wx_name']);
            $session->set('refereimages',$refereInfo['wx_images']);
        }else{
            $qcode = $session->get('qcode');
        }
        if(!$qcode) {
            return $this->redirect(Yii::$app->params['domurl']."wx/frontend/web/html/detail/goods_detail.html?id=8fc674d0-bcc0-11e8-b05d-a53f0a637c51&userid=".$userid);
        }
        if($openid&&$userid&&$qcode)
        {
            $this->userSave($openid);
            return $this->redirect(Yii::$app->params['domurl']."wx/frontend/web/html/detail/goods_detail.html?id=8fc674d0-bcc0-11e8-b05d-a53f0a637c51&refereid=".$qcode."&userid=".$userid);
        }
    }

    public function actionGowxdp7()
    {
        //用户第二次进入
        $session = Yii::$app->session;
        $openid=$session->get('openid');
        $userid = $session->get('userid');

        $qcode = isset($_GET['qcode'])?$_GET['qcode']:'';
        $ordersn = isset($_GET['ordersn'])?$_GET['ordersn']:'';
        if($qcode){
            $session = Yii::$app->session;
            $refereInfo = Wxuser::findOne(['qcode'=>$qcode]);
            $session->set('ordersn',$ordersn);
            $session->set('qcode',$qcode);
            $session->set('referename',$refereInfo['wx_name']);
            $session->set('refereimages',$refereInfo['wx_images']);
        }else{
            $qcode = $session->get('qcode');
        }
        if(!$qcode) {
            return $this->redirect(Yii::$app->params['domurl']."wx/frontend/web/html/detail/goods_detail.html?id=2da50710-bcc1-11e8-86d0-c3161bb516f1&userid=".$userid);
        }
        if($openid&&$userid&&$qcode)
        {
            $this->userSave($openid);
            return $this->redirect(Yii::$app->params['domurl']."wx/frontend/web/html/detail/goods_detail.html?id=2da50710-bcc1-11e8-86d0-c3161bb516f1&refereid=".$qcode."&userid=".$userid);
        }
    }



    /**
     * 获取当前用户分享二维码
     *
     * @desc 获取当前用户分享二维码
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 500 服务器内部错误
     * @return mixed
     * @return \yii\web\Response
     * @throws Exception
     */
    public function actionGeterwurl()
    {
        $userid = Yii::$app->UserInfo->userid;
        $user = Wxuser::findOne($userid);
        if($user) {
            if($user->qcode_images) {
                $message = ['code'=>202,'message'=>'获取到用户分享码', 'qcode_images'=>$user->qcode_images];
                return json_encode($message);
            }
            $qcode = $user->qcode;
            $url = Yii::$app->params['domurl']."wx/frontend/web/index.php?r=site/site/gotourl&qcode=".$qcode;
            $message = ['code'=>200,'message'=>'用户路径获取成功', 'erwUrl'=>$url,'wx_images'=>$user->wx_images];
            return json_encode($message);
        }
    }

    public function actionGotourl()
    {
//        return $this->redirect('http://www.pooai.com/mobile/appDown.html');
        $qcode = isset($_GET['qcode'])?$_GET['qcode']:'';
        $ordersn = $this->GetOrderId($qcode);
        if($qcode&&$ordersn){
            return $this->redirect(Yii::$app->params['domurl']."wx/frontend/web/html/activity.html?qcode=$qcode&ordersn=$ordersn");
        }
    }

//    public function actionGodetail()
//    {
//        $qcode = $_GET['qcode'];
//        $ordersn = $_GET['ordersn'];
//        if($qcode&&$ordersn){
//
//        }else{
//            $post = Yii::$app->request->post();
//            $postData = $post['data'];
//            $qcode = $postData['qcode'];
//            $ordersn = $postData['ordersn'];
//        }
//        if($qcode) {
//            $url  = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5dee5a1c01f37b68&redirect_uri=".Yii::$app->params['domurl']."wx%2Ffrontend%2Fweb%2Findex.php%3Fr%3Dsite%252Fsite%252Fdetail%26qcode%3D$qcode%26ordersn%3D$ordersn&response_type=code&scope=snsapi_userinfo&state=authorize#wechat_redirect";
//            return $this->redirect($url);
//        }
//    }

    public function GetOrderId($qcode)
    {
        $id = Wxuser::findOne(['qcode'=>$qcode])->id;
        $ordersn = '';
        $orderInfoArrs = OrderInfo::find()->where(['user_id'=>$id,'pay_status'=>2])->all();
        foreach($orderInfoArrs as $k=>$model) {
            $num = OrderGoods::find()->where(['order_id'=>$model->order_id])->sum("goods_number");
            $useNum = OrderGoods::find()->where(['re_ordersn'=>$model->order_sn])->sum("goods_number");
            if($num*10>$useNum) {
                $ordersn = $model->order_sn;
                break;
            }
            $ordersn = $model->order_sn;
        }
        return $ordersn;
//        return OrderInfo::find()->where(['user_id'=>$id,'pay_status'=>2])->one()->order_sn;
    }

    /**
     * 获取当前页面上级用户信息
     *
     * @desc 获取当前页面上级用户信息
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 500 服务器内部错误
     * @return mixed
     * @return \yii\web\Response
     * @throws Exception
     */
    public function actionGetrefuser()
    {
        $session = Yii::$app->session;
        $refereInfo = array();
        if($session->get('qcode')) {
            $refereInfo['refereid']  = $session->get('qcode');
            $refereInfo['referename']  =$session->get('referename');
            $refereInfo['refereimages']  =$session->get('refereimages');
        } else{
            $post = Yii::$app->request->post();
            $refereid = isset($post['refereid'])?$post['refereid']:"";
            if($refereid) {
                $userARR = Wxuser::find()->where(['qcode'=>$refereid])->asArray()->one();

                if($userARR['is_gz']!==0){
                    $this->userSave($userARR['openid']);
                }

                $refereInfo['refereid']  =$userARR['qcode'];
                $refereInfo['referename']  =$userARR['wx_name'];
                $refereInfo['refereimages']  =$userARR['wx_images'];
                $message = ['code'=>200,'message'=>'用户路径获取成功', 'data'=>$refereInfo];
                return json_encode($message);
            }
        }
        $message = ['code'=>200,'message'=>'用户路径获取成功', 'data'=>$refereInfo];
        return json_encode($message);
    }

    /**
     * 获取当前用户信息
     *
     * @desc 获取当前用户信息
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 500 服务器内部错误
     * @return mixed
     * @return \yii\web\Response
     * @throws Exception
     */
    public function actionGetuserinfo()
    {
        $userid = Yii::$app->UserInfo->userid;
        $user = Wxuser::find()->where(['id'=>$userid])->asArray()->one();
        if($user['is_gz']!==0){
            $this->userSave($user['openid']);
        }
        $message = ['code'=>200,'message'=>'用户路径获取成功', 'data'=>$user];
        return json_encode($message);
    }

    /**
     * 微信授权登录，访问页面入口
     *
     * @desc 微信授权登录，访问页面入口，不需要其他参数验证，微信自己验证发送code,微信第二次访问时，不需要授权登录，需传入openid,userid
     * @param string $code |微信生成的code|yes|用户授权登录，向回调域发送code，回调域就是我们的程序地址|
     * @param string $acccess_token |第二次入口access_token|no|入口
     * @return array data 返回数据|验证信息
     * @return string data[].userid 用户ID
     * @return string data[].openid 用户名字
     * @return string data[].access_token 用户令牌
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 500 服务器内部错误
     * @return mixed
     * @return \yii\web\Response
     * @throws Exception
     */
    public function actionHgdetail()
    {
        //用户第二次进入
        $session = Yii::$app->session;
        $openid=$session->get('openid');
        $userid = $session->get('userid');
        if($openid&&$userid)
        {
            $this->userSave($openid);
            return $this->redirect(Yii::$app->params['goods_p8hg']."&userid=".$userid);
        }

        //用户首次进入，获取用户微信信息，需要的code
        $code = isset($_GET['code'])?$_GET['code']:'';
        if($code) {
            /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
            $wechat = Yii::$app->wechat;
            $wxInfo = $wechat->getOauth2AccessToken($code);
            $menberInfo = $wechat->getSnsMemberInfo($wxInfo['openid'],$wxInfo['access_token']);
            $menberInfo = $this->getMenInfo($menberInfo);

            //获取用户信息，判断是否新用户，自动添加用户到数据库，页面显示已登陆状态
            $user = Wxuser::findOne(['openid'=>$menberInfo['openid']]);
            if($user) {
//                ClickInfo::bClickInfo();
                $user->wx_name = $menberInfo['nickname'];
                $user->wx_images = $menberInfo['headimgurl'];
                $user->wx_name = $menberInfo['nickname'];
                $user->username = $menberInfo['nickname'];
                $user->sex = $menberInfo['sex'];
                $user->is_gz = $menberInfo['is_gz'];
                if($user->save()) {
                    $this->setSession($user);
                    return $this->redirect(Yii::$app->params['goods_p8hg']."&userid=".$user->id);
                }else{
                    throw new Exception(json_encode($user->errors));
                }
            } else {
                $user = new Wxuser();
                $user->openid = $wxInfo['openid'];
                $user->unionid = $openid;
                $user->wx_name = $menberInfo['nickname'];
                $user->wx_images = $menberInfo['headimgurl'];
                $user->wx_name = $menberInfo['nickname'];
                $user->username = $menberInfo['nickname'];
                $user->sex = $menberInfo['sex'];
                $user->is_gz = $menberInfo['is_gz'];
                if($user->save()) {
                    $this->setSession($user);
                    return $this->redirect(Yii::$app->params['goods_p8hg']."&userid=".$user->id);
                }else {
                    throw new Exception(json_encode($user->errors));
                }
            }
        } else {
            return 'aaa';
        }
    }

    /**
     * 微信授权登录，访问页面入口
     *
     * @desc 微信授权登录，访问页面入口，不需要其他参数验证，微信自己验证发送code,微信第二次访问时，不需要授权登录，需传入openid,userid
     * @param string $code |微信生成的code|yes|用户授权登录，向回调域发送code，回调域就是我们的程序地址|
     * @param string $acccess_token |第二次入口access_token|no|入口
     * @return array data 返回数据|验证信息
     * @return string data[].userid 用户ID
     * @return string data[].openid 用户名字
     * @return string data[].access_token 用户令牌
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 500 服务器内部错误
     * @return mixed
     * @return \yii\web\Response
     * @throws Exception
     */
    public function actionHgp7detail()
    {
        //用户第二次进入
        $session = Yii::$app->session;
        $openid=$session->get('openid');
        $userid = $session->get('userid');
        if($openid&&$userid)
        {
            $this->userSave($openid);
            return $this->redirect(Yii::$app->params['goods_p7hg']."&userid=".$userid);
        }

        //用户首次进入，获取用户微信信息，需要的code
        $code = isset($_GET['code'])?$_GET['code']:'';
        if($code) {
            /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
            $wechat = Yii::$app->wechat;
            $wxInfo = $wechat->getOauth2AccessToken($code);
            $menberInfo = $wechat->getSnsMemberInfo($wxInfo['openid'],$wxInfo['access_token']);
            $menberInfo = $this->getMenInfo($menberInfo);

            //获取用户信息，判断是否新用户，自动添加用户到数据库，页面显示已登陆状态
            $user = Wxuser::findOne(['openid'=>$menberInfo['openid']]);
            if($user) {
//                ClickInfo::bClickInfo();
                $user->wx_name = $menberInfo['nickname'];
                $user->wx_images = $menberInfo['headimgurl'];
                $user->wx_name = $menberInfo['nickname'];
                $user->username = $menberInfo['nickname'];
                $user->sex = $menberInfo['sex'];
                $user->is_gz = $menberInfo['is_gz'];
                if($user->save()) {
                    $this->setSession($user);
                    return $this->redirect(Yii::$app->params['goods_p7hg']."&userid=".$user->id);
                }else{
                    throw new Exception(json_encode($user->errors));
                }
            } else {
                $user = new Wxuser();
                $user->openid = $wxInfo['openid'];
                $user->unionid = $openid;
                $user->wx_name = $menberInfo['nickname'];
                $user->wx_images = $menberInfo['headimgurl'];
                $user->wx_name = $menberInfo['nickname'];
                $user->username = $menberInfo['nickname'];
                $user->sex = $menberInfo['sex'];
                $user->is_gz = $menberInfo['is_gz'];
                if($user->save()) {
                    $this->setSession($user);
                    return $this->redirect(Yii::$app->params['goods_p7hg']."&userid=".$user->id);
                }else {
                    throw new Exception(json_encode($user->errors));
                }
            }
        } else {
            return 'aaa';
        }
    }
}
